package com.gurid.service.oss.admin;

import com.gurid.common.base.result.R;
import com.gurid.common.base.result.ResultCode;
import com.gurid.common.base.util.ExceptionUtils;
import com.gurid.service.base.exception.GuridException;
import com.gurid.service.oss.service.FileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.media.SchemaProperty;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Tag(name = "七牛云文件管理")
//@CrossOrigin
@RestController
@RequestMapping("/admin/oss/file")
@Slf4j
public class FileController {

    @Autowired
    private FileService fileService;

    @Operation(summary = "文件上传")
    @PostMapping("upload")
    public R upload(
            //@Parameter(description = "file")
            @RequestBody(
                    content = @Content(
                            mediaType = "multipart/form-data",
                            schema = @Schema(type = "object"),
                            schemaProperties = {
                                    @SchemaProperty(name = "file", schema = @Schema(type = "string", format = "binary"))
                            })) MultipartFile file,

            @Parameter(description = "OSS归类模块", required = true)
                @RequestParam("module") String module){

        String upload = null;
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            upload = fileService.upload(inputStream, module, originalFilename);
        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new GuridException(ResultCode.FILE_UPLOAD_ERROR);
        }

        return R.ok().message("文件上传成功").data("url", upload);
    }

    @Operation(summary = "文件删除")//文件删除前端调用无效
    @DeleteMapping("remove")
    public R delete(
            @Parameter(description = "要删除的OSS文件url", required = true)
            @org.springframework.web.bind.annotation.RequestBody String url){
        fileService.delete(url);

        return R.ok().message("文件删除成功");
    }

    //微服务Feign测试
    @Operation(summary = "测试")
    @GetMapping("test")
    public R test(){
        log.info("oss test被调用");
        return R.ok();
    }
}
